﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using produccion.clases;
using System.Data;

namespace produccion.forms
{
    /// <summary>
    /// Lógica de interacción para frmControl.xaml
    /// </summary>
    public partial class FRMControl : Window
    {
        CLSCONTROLP Control = new CLSCONTROLP();
        DataTable dt = new DataTable();
        Boolean Nuevo = false;
        MDOgeneral mod = new MDOgeneral();

        public FRMControl()
        {
            InitializeComponent();
        }

        private void btnSalir_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void btnNuevo_Click(object sender, RoutedEventArgs e)
        {
            Nuevo = true;
            LimpiarCampos();
            Control.LimpiarValores();
        }

        private void LimpiarCampos()
        {
            txtId.Text = "";
            txtCod.Text = "";
            txtNom.Text = "";
            txtDes.Text = "";
        }

        private void btnGrabar_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Control.ID_CON = txtId.Text;
                Control.COD_CON = txtCod.Text;
                Control.NOM_CON = txtNom.Text;
                Control.DES_CON = txtDes.Text;
                if (!Control.ExisteControl())
                {
                    Control.Insertar();
                }
                else
                {
                    Control.Actualizar();
                }
                Control.LimpiarValores();
                LimpiarCampos();
                dt = Control.ConsultarTodas();
                dgControl.ItemsSource = dt.DefaultView;
                Nuevo = false;
                new MDOgeneral.notificar(wPnot, "Los cambios fueron guardados correctamente.", true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error al grabar parámetros de control",MessageBoxButton.OK, MessageBoxImage.Error);
                new MDOgeneral.notificar(wPnot, "Los cambios no pueden ser guardados correctamente.", false);
            }

        }

        private void btnEliminar_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (MessageBox.Show("Realmente desea eliminar el parámetro de control?", "Parámetros de control", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    Control.ID_CON = txtId.Text;
                    Control.COD_CON = txtCod.Text;
                    Control.NOM_CON = txtNom.Text;
                    Control.DES_CON = txtDes.Text;
                    Control.Eliminar();
                    Control.LimpiarValores();
                    LimpiarCampos();
                    dt = Control.ConsultarTodas();
                    dgControl.ItemsSource = dt.DefaultView;
                }
                Nuevo = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error al eliminar parámetros de control", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            dt = Control.ConsultarTodas();
            DataView dv = new DataView();
            dv = dt.DefaultView;
            
            dgControl.ItemsSource = dt.DefaultView;
        }

        private void dgControl_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (dgControl.SelectedIndex > -1)
                {
                    txtId.Text = ((DataRowView)dgControl.Items[dgControl.SelectedIndex]).Row["id_con"].ToString();
                    txtCod.Text = ((DataRowView)dgControl.Items[dgControl.SelectedIndex]).Row["cod_con"].ToString();
                    txtNom.Text = ((DataRowView)dgControl.Items[dgControl.SelectedIndex]).Row["nom_con"].ToString();
                    txtDes.Text = ((DataRowView)dgControl.Items[dgControl.SelectedIndex]).Row["des_con"].ToString();
                    expInfo.IsExpanded = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error al cargar controles con doble click del mouse", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void btnBuscar_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string CodControl;
                int Guion;
                FRMbuscar frm = new FRMbuscar(Control, "Buscar", "Codigo", "NOM_CON", "Codigo");
                frm.ShowDialog();
                CodControl = frm.retorno;
                Guion = CodControl.IndexOf("-");
                txtId.Text = CodControl.Substring(0, Guion);
                txtCod.Text = CodControl.Substring(Guion + 1, CodControl.Length - (Guion + 1));
                if (!txtId.Text.Equals("") & !txtCod.Text.Equals(""))
                {
                    Control.ID_CON = txtId.Text;
                    Control.COD_CON = txtCod.Text;
                    Control.Consultar();
                    txtNom.Text = Control.NOM_CON;
                    txtDes.Text = Control.DES_CON;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error al buscar parámetros de control", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void txtCod_TextChanged(object sender, TextChangedEventArgs e)
        {
        }

        private void txtId_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                txtCod.Focus();
            }
        }

        private void txtCod_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                txtNom.Focus();
            }
        }

        private void txtNom_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                txtDes.Focus();
            }
        }


        //Pone el filtro al cerrar el menu contextual
        private void cm_Closed(object sender, RoutedEventArgs e)
        {
               
        }



        private void button1_Click(object sender, RoutedEventArgs e)
        {
            DataTable a =new DataTable();
            dgControl.ItemsSource = null;
            dgControl.Items.Clear();
            dgControl.Columns.Clear();
            a = mod.MP_FiltrarDataTable(dt, "des_con like '%LINEA%'", "");
            dgControl.ItemsSource = a.DefaultView;
        }

        private void dgControl_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {            

        }

        private void txtFiltro_KeyDown(object sender, KeyEventArgs e)
        {
            DataTable dtFiltro=new DataTable();
            if (e.Key == Key.Enter)
            {
                if (txtFiltro.Text != "")
                {
                    int j = dgControl.CurrentCell.Column.DisplayIndex;
                    if (j == 0)
                    {
                        dtFiltro = mod.MP_FiltrarDataTable(dt, "ID_CON LIKE '%" + txtFiltro.Text + "%'", "");
                    }
                    if (j == 1)
                    {
                        dtFiltro = mod.MP_FiltrarDataTable(dt, "COD_CON LIKE '%" + txtFiltro.Text + "%'", "");
                    }
                    if (j == 2)
                    {
                        dtFiltro = mod.MP_FiltrarDataTable(dt, "NOM_CON LIKE '%" + txtFiltro.Text + "%'", "");
                    }
                    if (j == 3)
                    {
                        dtFiltro = mod.MP_FiltrarDataTable(dt, "DES_CON LIKE '%" + txtFiltro.Text + "%'", "");
                    }
                    dgControl.ItemsSource = null;
                    dgControl.Items.Clear();
                    dgControl.Columns.Clear();
                    dgControl.ItemsSource = dtFiltro.DefaultView;
                }
                else
                {
                    dgControl.ItemsSource = dt.DefaultView;
                }
            }
        }

        private void dgControl_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            var elemento = e.OriginalSource as UIElement;
            if (e.Key == Key.Enter && elemento != null)
            {
                e.Handled = true;
                elemento.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
            }
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            var elemento = e.OriginalSource as UIElement;
            if (e.Key == Key.F3 && elemento != null)
            {
                if (MDOgeneral.logBusquedadAbierta == true) { MDOgeneral.logBusquedadAbierta = false; }
            }

            if (e.Key == Key.F4 && elemento != null)
            {
                if (MDOgeneral.logBusquedadAbierta1 == true) { MDOgeneral.logBusquedadAbierta1 = false; }
            }

            if (e.Key == Key.F5 && elemento != null)
            {
                if (MDOgeneral.logBusquedadAbierta2 == true) { MDOgeneral.logBusquedadAbierta2 = false; }
            }
        }

    }

    internal class ValidarId : ValidationRule
    {
        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            if (value.ToString() == null)
            {
                return new ValidationResult(false, "La identificación no puede estar nulo");
            }
            if (value.ToString().Trim().Equals(""))
            {
                return new ValidationResult(false, "La identificación no puede estar vacío");
            }
            return new ValidationResult(true, null);
        }
    }

    internal class ValidarCod : ValidationRule
    {
        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            if (value.ToString() == null)
            {
                return new ValidationResult(false, "El código no puede estar nulo");
            }
            if (value.ToString().Trim().Equals(""))
            {
                return new ValidationResult(false, "El código no puede estar vacío");
            }
            return new ValidationResult(true, null);
        }
    }

    internal class ValidarNom : ValidationRule
    {
        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            if (value.ToString() == null)
            {
                return new ValidationResult(false, "El nombre no puede estar nulo");
            }
            if (value.ToString().Trim().Equals(""))
            {
                return new ValidationResult(false, "El nombre no puede estar vacío");
            }
            return new ValidationResult(true, null);
        }
    }

    internal class ValidarDes : ValidationRule
    {
        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            if (value.ToString() == null)
            {
                return new ValidationResult(false, "La descripción no puede estar nula");
            }
            if (value.ToString().Trim().Equals(""))
            {
                return new ValidationResult(false, "La descripción no puede estar vacía");
            }
            return new ValidationResult(true, null);
        }
    }
}
